#define _CRT_SECURE_NO_WARNINGS
#include<vector>
#include<stack>
using namespace std;
struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};
vector<int> postorderTraversal(TreeNode* root) {
    vector<int> v;
    stack<TreeNode*> s;
    TreeNode* cur = root;
    TreeNode* last = nullptr;
    while (cur || !s.empty()) {
        while (cur) {
            s.push(cur);
            cur = cur->left;
        }
        TreeNode* top = s.top();
        if (last == top->right || top->right == nullptr) {
            v.push_back(top->val);
            s.pop();
            last = top;
        }
        else cur = top->right;
    }
    return v;
}
